from jenkins import Jenkins
from django.core.cache import cache
from conf import public
import time
import threading
import queue

class Jenkins_build():
    def __init__(self):
        self.jenkins_url = public.jenkins_url
        self.username = public.username
        self.passwd = public.passwd
        self.jenkins_server = Jenkins(self.jenkins_url, username=self.username, password=self.passwd)

    def Start_thread(self, item_lists):
        for i in item_lists:
            t = threading.Thread(target=self.job_build,args=(i,))
            t.start()

    def job_build(self, items):
        self.jenkins_server.build_job(items)
        time.sleep(15)

        build_data = self.jenkins_server.get_job_info(items)
        end_build_id = build_data['lastBuild']["number"]
        status = True
        while status:
            build_status = self.jenkins_server.get_build_info(items, end_build_id)
            if not build_status["building"]:
                return_data = {}
                return_data[items] = [build_status["result"], build_status["changeSet"]["revisions"][0]["revision"]]
                status = False
                cache.set(items, return_data)
            else:
                print("%s 正在构建" % items)
                time.sleep(5)
